package com.stone.oauth.service;

import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>Created with IntelliJ IDEA. </p>
 * <p>User: Stony </p>
 * <p>Date: 2016/7/7 </p>
 * <p>Time: 13:04 </p>
 * <p>Version: 1.0 </p>
 */
@Service("authService")
public class AuthService {
    public static final int DEFAULT_CACHE_LIMIT = 1024;
    private volatile int cacheLimit = DEFAULT_CACHE_LIMIT;
    private static Map<String, Object> CACHE_CODE = new ConcurrentHashMap<>();
    private static Map<String, Object> CACHE_CLIENT_ID = new ConcurrentHashMap<>();
    private static Map<String, Object> CACHE_TOKEN = new ConcurrentHashMap<>();

    private final Map<String, Object> CACHE_CODE_LIMIT = new LinkedHashMap<String, Object>(DEFAULT_CACHE_LIMIT, 0.75f, true){
        @Override
        protected boolean removeEldestEntry(Map.Entry<String, Object> eldest) {
            if (size() > getCacheLimit()) {
                CACHE_CODE.remove(eldest.getKey());
                return true;
            }
            else {
                return false;
            }
        }
    };
    static {
        CACHE_CLIENT_ID.put("12345","123456");
        CACHE_CLIENT_ID.put("22345","223456");
    }

    public boolean checkClient(String clientId){
        return null == CACHE_CLIENT_ID.get(clientId);
    }
    public boolean checkCode(String code){
        return  null == CACHE_CODE.get(code);
    }
    public String getCodeValue(String code){
        return (String) CACHE_CODE.get(code);
    }
    public void addCode(String code,String username){
        CACHE_CODE.put(code, username);
        CACHE_CODE_LIMIT.put(code, username);
    }
    public void delCode(String code){
        CACHE_CODE.remove(code);
    }

    public void addToken(String token,String username){
        CACHE_TOKEN.put(token, username);
    }
    public boolean checkToken(String token){
        return null == CACHE_TOKEN.get(token);
    }

    public String getTokenValue(String token) {
        return (String) CACHE_TOKEN.get(token);
    }

    public void setCacheLimit(int cacheLimit) {
        this.cacheLimit = cacheLimit;
    }
    public int getCacheLimit() {
        return this.cacheLimit;
    }

}
